package jh.activity

import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ProgressBar
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.jh.ios.forecast.R
import constans.P
import jh.adapter.PersonalCommunityAdapter
import jh.interfaces.OnItemPictureClickListener
import jh.model.CModel
import jh.model.UserModel
import jh.utils.HttpUtils
import jh.utils.NavigationBar
import jh.utils.NoDoubleClickListener
import kotlinx.android.synthetic.main.acitvity_personal_community.*
import org.jetbrains.anko.toast
import org.json.JSONException
import java.util.*

/**
 * Created by apple on 2019/6/5.
 */
class PersonalCommunityActivity : BaseActivity(){
    private var progressBar: ProgressBar? = null
    private var rightItem: LinearLayout? = null
    var cmodleSeri: CModel? = null   //被评论人实体bean
    private var userModel: UserModel? = null  //用户实体bean
    private var page = 1
    private val size = 20
    private var adapter: PersonalCommunityAdapter? = null
    private val datas = ArrayList<CModel>()
    private var itemPosition: Int = 0

    private var mCodel: CModel? = null  //楼中楼评论临时实体bean

    override fun getLayoutId(): Int {
        return R.layout.acitvity_personal_community
    }

    override fun initData(savedInstanceState: Bundle?) {
        userModel = UserModel.getUserInfo(this)
        cmodleSeri = intent.getSerializableExtra("CModel") as CModel
        datas.add(cmodleSeri as CModel)   //添加第一条
        getData()
    }

    override fun initView() {

        backButton = find(R.id.back_buton)
        showBackButton()
        title = find(R.id.navigation_title)
        title.text = "交流圈"

        progressBar = find<ProgressBar>(R.id.progressBar)
//        progressBar?.visibility=View.GONE   //隐藏进度条

        rightItem = find(R.id.navigation_item)
        rightItem?.visibility = View.GONE  //隐藏发表按钮


        adapter = PersonalCommunityAdapter(this, datas, OnItemPictureClickListener { item, position, url, urlList, imageView ->
            itemPosition = item
            val intent = Intent(this@PersonalCommunityActivity, ImagePreviewActivity::class.java)
            intent.putStringArrayListExtra("imageList", urlList as ArrayList<String>)
            intent.putExtra(P.START_ITEM_POSITION, itemPosition)
            intent.putExtra(P.START_IAMGE_POSITION, position)
            val compat = ActivityOptions.makeSceneTransitionAnimation(this@PersonalCommunityActivity, imageView, imageView.transitionName)
            startActivity(intent, compat.toBundle())
        })

        list_view.adapter = adapter
        list_view.setInteface({
            page++
            getData()
        })

        swipe_refresh.setColorSchemeResources(R.color.colorMain)
        swipe_refresh.setOnRefreshListener({
//            datas.clear()
            page = 1
//            datas.add(cmodleSeri as CModel)   //清空数据后重新添加第一条
            getData()
        })
        swipe_refresh.isRefreshing = true

        adapter?.setaaListener(object : PersonalCommunityAdapter.Listener<CModel> {
            override fun onClick(a: CModel) {
                mCodel = a  //临时存储Cmodel
                et_reply.hint = "@${a.nickName}"
                openKeybord(et_reply, this@PersonalCommunityActivity)
            }

        })

        et_reply.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val str = s.toString()
                if (str.isNotBlank()) {  //字符串判空
                    tv_reply.setBackgroundResource(R.drawable.ball_rect_shape_orange)
//                    tv_reply.setOnClickListener(this@PersonalCommunityActivity)
                    tv_reply.setOnClickListener(object : NoDoubleClickListener() {
                        override fun onNoDoubleClick(v: View?) {
                            sendData(et_reply.text.toString())
                        }
                    })
                } else {
                    tv_reply.setBackgroundResource(R.drawable.ball_rect_shape)
                    tv_reply.setOnClickListener(null)
                }
            }

        })

        //控制软键盘
        addLayoutListener(ll_origin_layout, ll_bottom, v_softkeyboard)
    }

    private fun sendData(comment: String) {
        val url = "/api/communicationCircleDetail/insertCommunicationCircleDetail"

        val map = HashMap<String, String>()
        if (userModel != null) {
            map.put("loginToken", userModel?.loginToken!!)
            map.put("content", comment)
            map.put("replyId", "${userModel?.uid}")   //replyid对应uid
            map.put("ccId", "${cmodleSeri?.id}")      //ccid对应id
            if (mCodel == null) {
                map.put("detailId", "")
            } else {
                map.put("detailId", "${mCodel?.id}")
            }
        }

        HttpUtils.POST(url, map) { `object`, msg, e ->
            progressBar?.visibility = View.GONE
            swipe_refresh.visibility = View.VISIBLE
            swipe_refresh.isRefreshing = false
            if (e == null) {
                if (msg == null) {
                    et_reply.setText("")
                    et_reply.hint = "回复"
                    mCodel = null
                    closeKeyBord()
                    //回复成功，重新获取评论列表，刷新列表
//                    datas.clear()
//                    datas.add(cmodleSeri as CModel)   //清空数据后重新添加第一条
                    page = 1
                    getData()

                }
            }
        }
    }

    /**
     * 关闭软键盘
     */
    private fun closeKeyBord() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(et_reply.windowToken, 0)
    }

    /**
     * 打开软键盘
     *
     * @param mEditText
     * @param mContext
     */
    fun openKeybord(mEditText: EditText, mContext: Context) {
        val imm = mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN)
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY)
    }


    //设置文本字体颜色
    val textColorFormat = "<font color=\"#222222\">%1s</font><font color=\"#ff8110\">%2s</font><font color=\"#808080\">%3s</font>"

    private fun getData() {

        val url = "/api/communicationCircleDetail/getCommunicationDetailsByCcId"

        val map = HashMap<String, String>()
        map.put("page", "$page")
        map.put("size", "$size")
        if (userModel != null) {
            map.put("ccId", cmodleSeri?.id!!.toString() + "")
            map.put("loginToken", userModel?.loginToken!!)
        }

        HttpUtils.POST(url, map) { `object`, msg, e ->
            progressBar?.visibility = View.GONE
            swipe_refresh.visibility = View.VISIBLE
            swipe_refresh.isRefreshing = false
            if (e == null) {
                if (msg == null) {
                    try {
                        val jsonArray = `object`.getJSONArray("data")
                        val builder = GsonBuilder()
                        val gson = builder.create()
                        val list = gson.fromJson<List<CModel>>(jsonArray.toString(), object : TypeToken<List<CModel>>() {

                        }.type)
                        if (list.isEmpty()) {   //分页没有更多数据
//                            if(page>1) toast("没有更多数据")
                        } else {

                            list.forEachIndexed { index, cModel ->
                                if (cModel.detailId != null) {
                                    list.forEachIndexed { index, c ->
                                        if (cModel.detailId?.toInt() == c.id) {
                                            val s = String.format(textColorFormat, "${cModel.content} ", "@${c.nickName}", ": ${c.content}")
                                            cModel.mContent = s
                                        }
                                    }
                                }
                            }
                            if(page==1){
                                datas.clear()
                                datas.add(cmodleSeri as CModel)   //添加第一条
                            }
                            datas.addAll(list)
                            adapter?.notifyDataSetChanged()
                        }
                        list_view.loadComplete()
                    } catch (e1: JSONException) {
                        e1.printStackTrace()
                    }

                }
            }
        }
    }

    private fun addLayoutListener(main: View, scroll: View, foot: View) {
        main.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            main.getWindowVisibleDisplayFrame(rect)
            val mainInvisibleHeight = main.rootView.height - NavigationBar.getNavigationBarHeight(this) - (rect.bottom - rect.top)

            // 100   200   260   分辨率由低到高
            if (mainInvisibleHeight > 260) {    //针对三星变态的 2960x1440像素 分辨率设置
                if (foot.visibility == View.GONE || foot.layoutParams.height <= 0) {
                    val location = IntArray(2)
                    scroll.getLocationInWindow(location)
                    val srollHeight = location[1] + scroll.height - rect.bottom

                    //main.scrollTo(0, srollHeight);
                    val Params = foot.layoutParams
                    Params.height = srollHeight
                    foot.layoutParams = Params


                    foot.visibility = View.VISIBLE

//                    app_title.visibility = View.GONE


                }
            } else {
                //main.scrollTo(0, 0);
                foot.visibility = View.GONE
//                if (app_title.visibility == View.GONE) {
//                    app_title.visibility = View.VISIBLE
//                }
            }

        }
    }

//    override fun onClick(v: View?) {
//        super.onClick(v)
//        when (v) {
//            tv_reply -> {
//                sendData(et_reply.text.toString())
//            }
//        }
//    }
}